package com.jt.provider.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Slf4j //為類創建一個log對象
@RefreshScope
@RestController
public class ProviderCacheController {
//    private static final Logger log=
//            LoggerFactory.getLogger(ProviderCacheController.class);
    /**
     * 從配置文件讀取配置賦值給屬性
     */
    @Value("${useLocalCache:false}")
    private boolean useLocalCache;

    @GetMapping("/provider/cache01")
    public String doUseLocalCache01(){
        return String.format("useLocalCache's value is %s",useLocalCache);
    }
    //定义一个集合作为一个本地Cache(缓存)
    private CopyOnWriteArrayList<String> cache=new CopyOnWriteArrayList<>();
    @GetMapping("/provider/cache02")
    public  List<String> doUseLocalCache02(){
        if(!useLocalCache){//假如useLocalCache的值为false,表示不开启本地cache.
           log.info("select data from database");
           return Arrays.asList("A","B","C");//假设这些数据来自数据库
        }
        if(cache.isEmpty()){
          synchronized (this) {
             if (cache.isEmpty()) {
                //模拟从数据库获取数据
                log.info("select data from database");
                List<String> data = Arrays.asList("A", "B", "C");
                //将数据放入cache中
                cache.addAll(data);
             }
          }
        }
        log.info("select data from cache");
        return cache;
    }

}
